package com.ruoyi.dept.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.base.domain.bo.SysMessageInfoBo;
import com.ruoyi.base.domain.vo.SysMessageInfoVo;
import com.ruoyi.base.service.ISysMessageInfoService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.dept.domain.BsDepartment;
import com.ruoyi.dept.mapper.BsDepartmentMapper;
import com.ruoyi.sycs.domain.BaQjDetail;
import com.ruoyi.sycs.domain.bo.BaQjDetailBo;
import com.ruoyi.sycs.domain.vo.BaQjDetailVo;
import liquibase.pro.packaged.B;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.ruoyi.dept.domain.bo.BsInstrumentBo;
import com.ruoyi.dept.domain.vo.BsInstrumentVo;
import com.ruoyi.dept.domain.BsInstrument;
import com.ruoyi.dept.mapper.BsInstrumentMapper;
import com.ruoyi.dept.service.IBsInstrumentService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 试验室仪器Service业务层处理
 *
 * @author zyb
 * @date 2024-04-22
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional
public class BsInstrumentServiceImpl implements IBsInstrumentService {

    private final BsInstrumentMapper baseMapper;

    private final BsDepartmentMapper departmentMapper;

    private final ISysMessageInfoService messageInfoService;

    /**
     * 查询试验室仪器
     */
    @Override
    public BsInstrumentVo queryById(Long instruId){
        return baseMapper.selectVoById(instruId);
    }

    /**
     * 查询试验室仪器列表
     */
    @Override
    public TableDataInfo<BsInstrumentVo> queryPageList(BsInstrumentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BsInstrument> lqw = buildQueryWrapper(bo);
        Page<BsInstrumentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<BsDepartment> bsDepartments = departmentMapper.selectList();
        result.getRecords().forEach(t -> {
            Optional.ofNullable(t.getDpmId())
                .ifPresent(dpmId -> bsDepartments.stream()
                    .filter(s -> dpmId.equals(s.getId().toString()))
                    .findFirst()
                    .ifPresent(s -> t.setDpmId(s.getName())));
        });

        return TableDataInfo.build(result);
    }

    /**
     * 查询试验室仪器列表
     */
    @Override
    public List<BsInstrumentVo> queryList(BsInstrumentBo bo) {
        LambdaQueryWrapper<BsInstrument> lqw = buildQueryWrapper(bo);
        List<BsInstrumentVo> bsInstrumentVos = baseMapper.selectVoList(lqw);
        List<BsDepartment> bsDepartments = departmentMapper.selectList();
        bsInstrumentVos.forEach(t -> {
            Optional.ofNullable(t.getDpmId())
                .ifPresent(dpmId -> bsDepartments.stream()
                    .filter(s -> dpmId.equals(s.getId().toString()))
                    .findFirst()
                    .ifPresent(s -> t.setDpmId(s.getName())));
        });
        return bsInstrumentVos;
    }

    private LambdaQueryWrapper<BsInstrument> buildQueryWrapper(BsInstrumentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BsInstrument> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDpmId() != null, BsInstrument::getDpmId, bo.getDpmId());
        lqw.eq(bo.getDeptId() != null, BsInstrument::getDeptId, bo.getDeptId());
        lqw.like(StringUtils.isNotBlank(bo.getInstruName()), BsInstrument::getInstruName, bo.getInstruName());
        lqw.eq(bo.getDeptId() != null, BsInstrument::getDeptId, bo.getDeptId());
        lqw.eq(StringUtils.isNotBlank(bo.getManufacturer()), BsInstrument::getManufacturer, bo.getManufacturer());
        lqw.eq(StringUtils.isNotBlank(bo.getModel()), BsInstrument::getModel, bo.getModel());
        lqw.eq(StringUtils.isNotBlank(bo.getMeasuringRange()), BsInstrument::getMeasuringRange, bo.getMeasuringRange());
        lqw.eq(StringUtils.isNotBlank(bo.getManufacturerCode()), BsInstrument::getManufacturerCode, bo.getManufacturerCode());
        lqw.eq(bo.getManufacturerDate() != null, BsInstrument::getManufacturerDate, bo.getManufacturerDate());
        lqw.eq(bo.getPurchaseDate() != null, BsInstrument::getPurchaseDate, bo.getPurchaseDate());
        lqw.eq(StringUtils.isNotBlank(bo.getCustodian()), BsInstrument::getCustodian, bo.getCustodian());
        lqw.eq(StringUtils.isNotBlank(bo.getCalibrationUnit()), BsInstrument::getCalibrationUnit, bo.getCalibrationUnit());
        lqw.eq(bo.getCalibrationDate() != null, BsInstrument::getCalibrationDate, bo.getCalibrationDate());
        lqw.eq(bo.getEffectiveDate() != null, BsInstrument::getEffectiveDate, bo.getEffectiveDate());
        lqw.eq(StringUtils.isNotBlank(bo.getRecordFlag()), BsInstrument::getRecordFlag, bo.getRecordFlag());
        return lqw;
    }

    /**
     * 新增试验室仪器
     */
    @Override
    @DSTransactional
    public Boolean insertByBo(BsInstrumentBo bo) {
        BsInstrument add = BeanUtil.toBean(bo, BsInstrument.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setInstruId(add.getInstruId());
            //判断是否需要新增消息通知逻辑
            if (Objects.nonNull(bo.getEffectiveDate())){
                messageInfoService.insertByBo(new SysMessageInfoBo(add.getInstruId(),"bs_instrument"));
            }
        }
        return flag;
    }

    /**
     * 修改试验室仪器
     */
    @Override
    @DSTransactional
    public Boolean updateByBo(BsInstrumentBo bo) {
        BsInstrument update = BeanUtil.toBean(bo, BsInstrument.class);
        validEntityBeforeSave(update);
        //判断是否需要修改消息通知逻辑
        boolean flag = baseMapper.updateById(update) > 0;
        if (Objects.nonNull(bo.getEffectiveDate()) && flag){
            List<SysMessageInfoVo> infoVos = messageInfoService.queryListByBusinessId(new SysMessageInfoBo(update.getInstruId(),""));
            if (CollectionUtils.isNotEmpty(infoVos)){
                messageInfoService.updateByBo(BeanUtil.toBean(infoVos.get(0), SysMessageInfoBo.class));
            }else {
                messageInfoService.insertByBo(new SysMessageInfoBo(update.getInstruId(),"bs_instrument"));
            }
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BsInstrument entity){
        //TODO 做一些数据校验,
        // 1.做一些业务上的校验，判断是否存在该条仪器消息通知，如有消息需判断是否修改时间修改消息内容调整时间，提供公共接口
    }

    /**
     * 批量删除试验室仪器
     */
    @Override
    @DSTransactional
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //删除消息通知
            messageInfoService.deleteWithValidByBusinessIds(ids, isValid);
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @DSTransactional
    public Boolean saveBatch(List<BsInstrument> list, boolean isUpdateSupport) {
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(v->{
                BsInstrumentVo maybeExistVo = baseMapper.selectVoOne(new LambdaQueryWrapper<BsInstrument>()
                    .eq(BsInstrument::getDeptId, v.getDeptId())
                    .eq(BsInstrument::getDpmId, v.getDpmId())
                    .eq(BsInstrument::getInstruName, v.getInstruName()));
                if (ObjUtil.isNull(maybeExistVo)) {
                    insertByBo(BeanUtil.toBean(v, BsInstrumentBo.class));
                    if (Objects.nonNull(v.getEffectiveDate())) {
                        messageInfoService.insertByBo(new SysMessageInfoBo(v.getInstruId(), "bs_instrument"));
                    }
                } else if (isUpdateSupport) {
                    Long id = maybeExistVo.getInstruId();
                    v.setInstruId(id);
                    updateByBo(BeanUtil.toBean(v, BsInstrumentBo.class));
                } else {
                    throw new ServiceException(v.getDpmName() + "已存在" + v.getInstruName() + "仪器，请勿重复添加");
                }
            });
        }
        return true;
    }

    @Override
    @DSTransactional
    public void updateOrInsertSysMessageScheduled() {
        //判断是否到达预警阈值判断是否已有数据，有则更新，无则走新增
        log.info("试验室仪器预警定时任务执行中...");
        LambdaQueryWrapper<BsInstrument> lqw = buildQueryWrapper(new BsInstrumentBo());
        lqw.eq(BsInstrument::getDelFlag, "0");
        lqw.isNotNull(BsInstrument::getEffectiveDate);
        List<BsInstrumentVo> vos = baseMapper.selectVoList(lqw);
        if (CollectionUtils.isNotEmpty(vos)){
            for (BsInstrumentVo vo : vos){
                List<SysMessageInfoVo> infoVos = messageInfoService.queryListByBusinessId(new SysMessageInfoBo(vo.getInstruId(), ""));
                if (CollectionUtils.isNotEmpty(infoVos)){
                    messageInfoService.updateByBo(BeanUtil.toBean(infoVos.get(0), SysMessageInfoBo.class));
                }else {
                    messageInfoService.insertByBo(new SysMessageInfoBo(vo.getInstruId(),"bs_instrument"));
                }
            }
        }
        log.info("试验室仪器预警定时任务结束...");
    }
}
